#include "StdAfx.h"
#include "SampleMxFn.h"
#include <sstream>
#include "engine.h"

const char * const MatlabSampleFn::FunctionNameMatlabSampleFn = "Matlab Demo";

MatlabSampleFn::MatlabSampleFn(void) 
{
	_fnApi.SetFunctionName(MatlabSampleFn::FunctionNameMatlabSampleFn);
	_fnApi.SetFunctionDescription("Simple Matlab Function. Plots graph ");
									//inputs
	_fnApi.AddParamDef(new ProcParamDefString(0, "Script Name", "Name of the Matlab script to be run", ProcParamDef::input, 0, 500 ));
	_fnApi.AddParamDef(new ProcParamDefString(1, "Path", "Sets the location of the script", ProcParamDef::input, 0, 500 ));
	_fnApi.AddParamDef(new ProcParamDefString(2, "X-Axis Label", "Sets the label for the X-Axis", ProcParamDef::input, 0, 500 ));
									//outputs
	_fnApi.AddParamDef(new ProcParamDefInt(0, ProcParam::attribOutputParamNameResult, "0 is success", ProcParamDef::output, 0, 1));

	_fnApi.Validate();
}


MatlabSampleFn::~MatlabSampleFn(void)
{

}


bool MatlabSampleFn::Process(ImageProcStep *step, bool DebugMode)
{	
	bool rc = false;
	if ((step != '\0') && (step->IsValid()))
	{
		
		ProcParamString *pfname = dynamic_cast<ProcParamString *>(step->GetInputs()->GetParam(0));	//Check the Param number
		ProcParamString *pfpath = dynamic_cast<ProcParamString *>(step->GetInputs()->GetParam(1));
		ProcParamString *plabel = dynamic_cast<ProcParamString *>(step->GetInputs()->GetParam(2));
		//ProcParamInt *result = dynamic_cast<ProcParamInt *>(step->GetOutputs()->GetParam(0));		//Check the type and check the DefType
		if  (pfname != '\0' && pfpath != '\0' && plabel != '\0')
		{
			std::stringstream SSArg (std::stringstream::in | std::stringstream::out);
			const std::string fname = std::string(pfname->GetValueStr());
			const std::string fpath = std::string(pfpath->GetValueStr());
			const std::string label = std::string(plabel->GetValueStr());
			
			Engine *ep;
			if (ep = engOpen("\0"))
			{
				SSArg << "Path('" << fpath << "')";
				engEvalString(ep, SSArg.str().c_str());
				SSArg.str("");								//clearing SS
				SSArg << "TestMe(" << label << ")";
				engEvalString(ep, SSArg.str().c_str());
				engEvalString(ep, "close;");															// close MATLAB figure.
				rc = true;
			}	
		}
	}
	return rc;
}
